// $Id$
package de.servicezombie.cxf;

import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;

import de.servicezombie.pub.r1.CommonRestResponse;

public class WebserviceTemplateCxf24Impl implements WebserviceTemplate {
	
	private static final String RESPONSE = "de.servicezombie.cxf.rest.responseWrapper";
	
	private ServletApiAdapter adapter;
	
	protected WebserviceTemplateCxf24Impl() {
		init();
	}
	
	private void init() {
		Message message = PhaseInterceptorChain.getCurrentMessage();
		adapter = new JaxrsServletApiFactory().build(message);
	}
	
	public final Exchange getExchange() {
		Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
		if(currentMessage == null) {
			throw new IllegalStateException("No message available. This can only be called if a cxf message is available in this thread.");
		}
		
		Exchange exchange = currentMessage.getExchange();
		return exchange;
	}
	
	public final <T> CommonRestResponse<T> getWebserviceResponse() {
		Exchange exchange = getExchange();
		
		@SuppressWarnings("unchecked")
		CommonRestResponse<T> response = (CommonRestResponse<T>) exchange.get(RESPONSE); 
		
		if(response == null) {
			response = new CommonRestResponse<T>();
			exchange.put(RESPONSE, response);
		}
		
		return response;
	}

	public ServletApiAdapter getServletApiAdapter() {
		return adapter;
	}	
	
	@Override
	public final String toString() {
		String address = adapter != null ? adapter.getClientIP() : null;
		return getClass().getSimpleName() + " [" + address + "]";
	}
}
